package cst.a110lyj.spinnertest110;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity{
  private TextView tvinfo;
    private Spinner spinner;
    //String[] cities ={"北京","上海","天津","大连"};

   void init(){
       tvinfo =(TextView)findViewById(R.id.textView2);
       spinner =(Spinner)findViewById(R.id.spinner);
   }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        List<City> list =getData();
        String[] cities=new String[list.size()];//定义数据源
        for(int i=0;i<list.size();i++)
            cities[i]=list.get(i).getName();
    //创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item,cities);//数据源
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//下拉样式
        spinner.setAdapter(adapter);//设置监听事件
        spinner.setPrompt("请选择城市");
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long id ){
                tvinfo.setText("你选择的是 ： "+adapterView.getItemAtPosition(i).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }    


    public List<City> getData() {

        List<City> list=new ArrayList<City>();
        City c;

        c=new City();
        c.setName("北京");
        list.add(c);

        c=new City();
        c.setName("上海");
        list.add(c);

        c=new City();
        c.setName("广州");
        list.add(c);

        return list;

    }
}
